package com.javasm.util;

import com.javasm.entity.JINXIAOEntity.SysUser;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

//静态工具方法获取实例bean
@Component
public class BeanUtil implements ApplicationContextAware {
   /*1. ApplicaitonContextAware接口
   * 一个bean对象此ApplicaitonContextAware派生,重写setApplicationContext方法,可以得到spring容器对象的引用.
   *
   *封装ApplicationContext(当前容器对象) 在BeanUtil类中，方便直接调用
   *封装BeanUtil容器对象
   *
   *
   * */

    private static ApplicationContext applicationContext;
    @Override
    public void setApplicationContext(ApplicationContext ac) throws BeansException {
        applicationContext = ac;
    }

    public static Object getBean(String id){
        return applicationContext.getBean(id);
    }

    public static <T> T getBean(String id,Class<T> clz){
        Object bean = applicationContext.getBean(id);
        return (T)bean;
    }
    public static <T> T getBean(Class<T> clazz) {
        return applicationContext.getBean(clazz);
    }
    public static <T> T getbean(Class<T> clz){
        return applicationContext.getBean(clz);
    }

    public static void main(String[] args) {
        //在这个静态工具方法中或者子线程中调用容器中某个bean对象的方法,
        SysUser getbean = BeanUtil.getbean(SysUser.class);
        System.out.println(getbean);
    }

}

